<template>
  <view v-if="isLazyLoading" class="x-lazy-loading">
    <x-image src="/assets/images/pic-007.png" />
    <x-image src="/assets/images/pic-008.png" />
  </view>
</template>

<script>
import { mapState } from 'vuex';
import $config from '@/config';
import XImage from '@/components/x-image';

export default {
  name: 'Transit',
  components: {
    XImage
  },
  props: {},
  data() {
    return {
      isSaas: $config.project === 'saas',
      query: {},
      isGuessLike: false,
      isRankingList: false,
      isCouponCentre: false,
      isSubsidyList: false,
      isLazyLoading: false,
      orderCountInfo: null,
      isImmersive: true,
      // 是否加载过其他页面数据
      isLoadOther: false
    };
  },
  computed: {
    ...mapState({
      previousPath: state => state['pages'].previousPath,
      previousQuery: state => state['pages'].previousQuery,
      groupsInfo: state => state['pages'].groupsInfo,
      // app onShow 场景值
      scene: state => state['pages'].scene,
      // 投放页面初始数据
      pageQuery: state => state['pages'].pageQuery,
      // 用户挽留弹窗是否点击过确认按钮
      isConfirmPopup: state => state['pages'].isConfirmPopup,
      // 用户挽留弹框配置的优惠数组
      exitPopupList: state => state['pages'].exitPopupList || [],
      // 用户挽留弹框配置的优惠展示过的下标
      exitPopupIndex: state => state['pages'].exitPopupIndex,
      // 当前页面浏览状态
      previousStatus: state => Number(state['pages'].previousStatus),
      // 返回首页还是店铺主页的链接
      reLaunchUrl: state => state['product'].reLaunchUrl,
      // 页面信息
      pageInfo: state => state['product'].pageDetail,
      // 页面模块
      pageModule: state => state['product'].pageModule || {},
      // 主推商品
      primaryPageId: state => state['product'].primaryPageId,
      // 商品类目信息
      levelSecondId: state => state['product'].productDetail?.levelSecondId,
      levelSecondName: state => state['product'].productDetail?.levelSecondName
    }),
    adParams() {
      const { gdt_vid, qq_ac_id, qq_ag_id, clickid, adid, acode, callback, aid, cid, ksUnitId, ksSiteAccountId } = this.pageQuery || {};
      return {
        gdt_vid,
        qq_ac_id,
        qq_ag_id,
        clickid,
        adid,
        acode,
        callback,
        aid,
        cid,
        ksUnitId,
        ksSiteAccountId
      };
    }
  },
  watch: {},
  onLoad(options) {
    this.query = options;
    console.log('query->', this.query);
    if (options.scene) {
      const scene = this.$tools.param2Object(options.scene);
      if (scene.t) {
        this.query.td = scene.t;
      }
    }
    this.$store.dispatch('product/reset');
    this.$store.dispatch('pages/fetchAppStore');
    this.$store.dispatch('message/setData', {
      dialogSubscribeGuide: false
    });
    this.$store.dispatch('pages/setData', {
      pageQuery: options
    });
    this.$store.dispatch('product/setData', {
      reLaunchUrl: null,
      homeReLaunchUrl: null
    });

    // 当前场景值为视频号1228时，可用挽留弹窗状态调整为不可用
    // testScene 方便测试同学回归使用的场景值参数
    // 1011 1012 1013 1025 1031 1032 1047 1048 1049 扫码场景值
    if ([1200, 1201, 1228].includes(this.scene) || ['1228'].includes(this.query.testScene) || ([1011, 1012, 1013, 1025, 1031, 1032, 1047, 1048, 1049].includes(this.scene) && ![1, '1'].includes(this.query.td))) {
      this.$store.dispatch('pages/setData', {
        popupStatus: false
      });
    }
  },
  onShow() {
    this.handleShow();
  },
  onHide() {
    // 跳转逻辑：推广页=>视频号页面=>挽留弹框=>挽留页=>沉浸式=>关联商品=>好物=>店铺首页=>猜你喜欢=>榜单=>领券中心=>活动补贴=>商城首页
    // 下过单并且支付过，直接返回到 猜你喜欢
    const { orderCount, payCount } = this.orderCountInfo;
    let isLazyApi;
    if (this.previousStatus === 0) {
      isLazyApi = orderCount || payCount;
    } else if (this.isSaas) {
      isLazyApi = [1, 3, 11].includes(this.previousStatus);
    } else {
      isLazyApi = [3, 5, 11].includes(this.previousStatus);
    }
    if (isLazyApi && !this.isLoadOther) {
      // saas下没有店铺，所以场景5 不需要执行
      this.getGuessLikeData();
      this.getRankingListData();
      this.getCouponCentreData();
      this.getSubsidyListData();
      this.isLoadOther = true;
    }
    // 准备预加载内容
    if (this.previousStatus === 0) {
      setTimeout(() => {
        this.isLazyLoading = true;
      }, 1000);
    }
  },
  methods: {
    async handleShow() {
      // 重置一些参数
      this.$store.dispatch('pages/setData', {
        productCount: 1,
        payCancelTwoVisible: false,
        clearStoreStorage: true
      });
      // 再次返回页面的时候，更新缓存中的数据
      this.$XTrack('onLoad', this.query);
      //  从小程序码进入
      try {
        if (this.query.scene) {
          const scene = this.$tools.param2Object(this.query.scene);
          this.query.pageId = scene.id;
          this.query.pageType = scene.p;
          if (scene.t) {
            this.query.td = scene.t;
          }
          delete this.query.scene;
        } else {
          if (this.query.id) {
            this.query.pageId = this.query.id;
          }
          if (this.query.p) {
            this.query.pageType = this.query.p;
          }
          if (this.query.t) {
            this.query.td = this.query.t;
          }
        }
      } catch (e) {
        console.warn('query.scene->', e);
      }
      // 通过扫码进入投入页时，默认添加上gdt_vid参数，来判定为广告进入
      // 相册识别、长按识别，小程序码与普通二维码
      if ([1011, 1012, 1013, 1047, 1048, 1049].includes(this.scene)) {
        this.query.gdt_vid = this.query.gdt_vid || 1047;
      }
      console.log('previousStatus', this.previousStatus);
      console.log('exitPopupIndex', this.exitPopupIndex);
      if (this.query && this.query.pageId && !this.previousStatus) {
        const params = {
          ...this.query
        };
        // 查询当前用户是否下过单，支付过
        try {
          if (!this.orderCountInfo) {
            await this.getOrderCount();
            const { orderCount, payCount } = this.orderCountInfo;
            // 下过单，支付过，直接返回首页
            if (orderCount && payCount) {
              Object.assign(params, {
                previousStatus: 6
              });
            } else if (orderCount) {
              // 下过单，未支付过，给最大优惠
              Object.assign(params, {
                source: 1026,
                createdType: 1,
                previousStatus: 11
              });
            }
          }
        } catch (e) {
          console.warn('getOrderCount->', e);
        }
        const { immersiveVideoUrl } = await this.getPageDetail(this.query.pageId);
        if (immersiveVideoUrl) {
          this.videoUrl = immersiveVideoUrl;
        }
        const query = this.$tools.object2param(params);
        await this.getVideoInfo();
        // pageType，2:沉浸视频，其它普通
        const url = [2, 3, 4].includes(+this.query.pageType) && this.isImmersive ? `/pages/immersive/index?${query}` : `/pages/advertising/index?${query}`;
        wx.navigateTo({
          url
        });
      } else {
        const isStayPopup = this.exitPopupList && this.exitPopupList.length > 0 && this.exitPopupIndex < this.exitPopupList.length;
        // previousStatus
        // 0，初始
        // 1，刚进入投放页；
        // 2，展示挽留弹窗口，
        // 3，已经展示过挽留页(聚合页)
        // 4，已经展示过沉浸式视频
        // 5，已经展示过关联商品
        // 6，已经展示过店铺首页
        // 7，已经展示过猜你喜欢
        // 8，已经展示过榜单
        // 9，已经展示过领券中心
        // 10，已经展示过活动补贴
        // 11, 已经展示过好物推荐
        // 12, 已经展示过视频号
        // console.log('reLaunchUrl->', this.reLaunchUrl);
        switch (this.previousStatus) {
          case 12:
            // 视频号
            this.toChannels();
            break;
          case 1:
          case 2:
            if (isStayPopup) {
              // 配置有挽留页
              this.toStayPopup();
            } else {
              this.isStay();
            }
            break;
          case 3:
            // 前往沉浸式视频
            this.toImmersive();
            break;
          case 4:
            // 前往关联商品
            this.toAssociated();
            break;
          case 11:
            // 好物推荐
            this.toSwiper();
            break;
          case 5:
            // 店铺首页
            this.toStoreHome();
            break;
          case 6:
          case 7:
          case 8:
          case 9:
          case 10:
            // 榜单
            this.toOtherPage();
            break;
          case 99:
            // 直接回首页
            this.toHome();
            break;
          default:
            console.log('previousStatus->', this.previousStatus);
            break;
        }
      }
    },
    // 查询用户是否下过单
    async getOrderCount() {
      await this.$http({
        login: true,
        error: false,
        url: '/order/app/order/count',
        data: {
          pageId: this.query.pageId
        }
      }).then((res) => {
        this.orderCountInfo = res.data;
        this.$store.dispatch('pages/setData', {
          orderCountInfo: res.data
        });
      }).catch(() => {
        this.orderCountInfo = {
          orderCount: 0,
          payCount: 0
        };
      });
    },
    // 校验是否有聚合页
    async isStay() {
      if (this.groupsInfo) {
        console.log('groupsInfo-> ', this.groupsInfo, this.primaryPageId);
        const { pageId, pageType, discountAmount } = this.groupsInfo;
        let params = {
          ...this.previousQuery,
          pageId,
          discountAmount,
          source: 'groups'
        };
        // 如果是视频类型的页面，需要把相关参数带到普通落地页去
        if (this.previousPath === '/pages/immersive/index') {
          params.sourcePageType = 2;
        } else {
          params.sourcePageType = 1;
        }
        params.sourcePageId = this.previousQuery.pageId;
        // 展示过挽留弹窗之后去的聚合页
        if (this.previousStatus === 2) {
          Object.assign(params, {
            groupsSource: this.isConfirmPopup ? '2002' : '2001'
          });
        }
        if (pageType === 1) {
          if (this.primaryPageId) {
            // 校验主推商品是否上架状态
            const { pageStatus } = await this.getPageDetail(this.primaryPageId);
            if (pageStatus === 1) {
              params = {
                groupsType: 'advertising',
                source: 1030,
                pageId: this.primaryPageId,
                sourcePageId: pageId,
                td: this.query.td,
                ...this.adParams
              };
            }
          } else {
            Object.assign(params, {
              groupsType: 'advertising',
              pageId: this.groupsInfo.pageId,
              ...this.adParams
            });
          }
          this.toStayAdvertising(params);
        } else {
          // 有主推商品的时候
          if (this.primaryPageId) {
            Object.assign(params, {
              source: 1030,
              primaryPageId: this.primaryPageId,
              td: this.query.td,
              ...this.adParams
            });
          }
          this.toStayGroups(params);
        }
      } else {
        // 一键回流关闭，不走沉浸视频，走后续链路，前往关联商品
        this.toSwiper();
      }
    },
    // 前往沉浸式视频
    toImmersive() {
      const params = {
        ...this.query,
        previousStatus: 11,
        pageType: 2,
        source: 1022,
        useDiscount: 1 // 使用聚合页（最大）优惠
      };
      if (this.query.pageType || !this.pageQuery.immersiveVideoUrl) {
        // 已经是通过沉浸式视频过来的，或者没有配置沉浸式视频数据的
        console.log('前往关联产品列表页->');
        this.toSwiper();
      } else {
        const query = this.$tools.object2param(params);
        console.log('前往沉浸式视频-> ', query);
        this.getVideoInfo(this.pageQuery.immersiveVideoUrl);
        if (this.isImmersive) {
          uni.navigateTo({
            url: `/pages/immersive/index?${query}`
          });
        } else {
          this.toSwiper();
        }
      }
    },
    // 前往挽留聚合页
    toStayGroups(params) {
      const query = this.$tools.object2param(params);
      console.log('前往挽留聚合页-> ', query);
      uni.navigateTo({
        url: `/packages/promotion/index/index?${query}`
      });
    },
    // 前往挽留投放页
    toStayAdvertising(params) {
      const query = this.$tools.object2param(params);
      console.log('前往挽留投放页-> ', query);
      uni.navigateTo({
        url: `/pages/advertising/index?${query}`
      });
    },
    // 前往挽留投放页弹窗状态
    toStayPopup() {
      console.log('前往挽留投放页弹窗状态');
      // 获取当前挽留弹窗数据
      const { styleType, discountAmount } = this.exitPopupList[this.exitPopupIndex] || {};
      const params = {
        ...this.previousQuery,
        styleType,
        discountAmount,
        source: 'stay',
        previousStatus: 2
      };
      // 移除url参数中不需要的
      delete params.stock_id;
      delete params.associate;
      delete params.nonce;
      delete params.createdType;
      // 把当前挽留弹窗的优惠金额配置上
      const query = this.$tools.object2param(params);
      console.log(`${this.previousPath}?${query}`);
      uni.navigateTo({
        url: `${this.previousPath}?${query}`
      });
    },
    // 配置
    setHomeReLaunchUrl() {
      // 聚合页配置信息
      const { pageId } = this.previousQuery;
      const params = {
        pageId,
        source: 1004
      };
      // 首页缩略参数
      const query = this.$tools.object2param(params);
      if (this.primaryPageId) {
        this.$store.dispatch('product/setData', {
          homeReLaunchUrl: `/pages/swiper/index?${query}`
        });
      } else {
        this.$store.dispatch('product/setData', {
          homeReLaunchUrl: `/pages/advertising/index?${query}`
        });
      }
    },
    // 前往关联商品（好物超值购）
    toAssociated() {
      const { productId, storeId, pageId } = this.pageQuery || {};
      const params = {
        ...this.query,
        pageId,
        productId,
        storeId,
        primaryPageId: this.primaryPageId,
        previousStatus: 5
      };
      const query = this.$tools.object2param(params);
      console.log('前往联合商品-> ', query);
      uni.navigateTo({
        url: `/packages/promotion/associated/index?${query}`
      });
    },
    // 前往好物推荐
    toSwiper() {
      this.setHomeReLaunchUrl();
      if (this.primaryPageId) {
        const { pageId } = this.pageQuery || {};
        const params = {
          pageId,
          primaryPageId: this.primaryPageId,
          previousStatus: 4,
          ...this.adParams
        };
        const query = this.$tools.object2param(params);
        console.log('前往好物推荐-> ', query);
        // 清空缓存数据
        this.$store.dispatch('pages/fetchAppStore', {
          previousStatus: this.previousStatus
        });
        uni.navigateTo({
          url: `/pages/swiper/index?${query}`
        });
      } else {
        this.toAssociated();
      }
    },
    // 前往店铺首页
    toStoreHome() {
      console.log('前往店铺首页->', this.reLaunchUrl, !this.isSaas);
      // saas下没有店铺首页
      if (!this.isSaas && this.reLaunchUrl) {
        uni.navigateTo({
          url: this.reLaunchUrl
        });
        // 前往店铺首页
        this.$store.dispatch('product/setData', {
          reLaunchUrl: null
        });
      } else {
        this.getRankingListData();
        this.toOtherPage();
      }
    },
    // 查询猜你喜欢中是否有数据
    getGuessLikeData() {
      this.$http({
        login: true,
        url: '/product/app/guess/like'
      }).then((res) => {
        this.isGuessLike = res.data && res.data.length;
      });
    },
    // 查询榜单中是否有数据
    getRankingListData() {
      this.$http({
        url: '/product/app/iu/category/top',
        data: {
          levelSecondCategoryId: this.levelSecondId,
          pageSize: 1
        }
      }).then((res) => {
        this.isRankingList = res.data && res.data.length;
      });
    },
    // 查询领券中心中是否有数据
    getCouponCentreData() {
      this.$http({
        url: '/product/app/coupon/centre',
        data: {
          type: 2,
          pageSize: 1
        }
      }).then((res) => {
        this.isCouponCentre = res.data && res.data.length;
      });
    },
    // 查询活动补贴中是否有数据
    getSubsidyListData() {
      this.$http({
        url: '/product/app/spu/list',
        data: {
          productSource: 3,
          pageSize: 1
        }
      }).then((res) => {
        this.isSubsidyList = res.data && res.data.length;
      });
    },
    // 前往其他页面
    toOtherPage() {
      const { isGuessLike, isRankingList, isCouponCentre, isSubsidyList } = this;
      console.log({
        isGuessLike,
        isRankingList,
        isCouponCentre,
        isSubsidyList
      });
      if (this.isGuessLike) {
        uni.navigateTo({
          url: '/packages/activity/guess-like/index?source=transit'
        });
        this.isGuessLike = false;
      } else if (this.isRankingList) {
        uni.navigateTo({
          url: `/packages/ranking/list/index?id=${this.levelSecondId}&name=${this.levelSecondName}&source=transit`
        });
        this.isRankingList = false;
      } else if (this.isCouponCentre) {
        uni.navigateTo({
          url: '/packages/coupon/coupon-centre/index?source=transit'
        });
        this.isCouponCentre = false;
      } else if (this.isSubsidyList) {
        uni.navigateTo({
          url: '/packages/activity/subsidy/list?source=transit'
        });
        this.isSubsidyList = false;
      } else {
        this.toHome();
      }
    },
    // 前往商城首页
    toHome() {
      // 通过广告返回首页的时候，需要把首页的tag选中为商城
      uni.setStorageSync('HOME-TABS-ACTIVE', 'mall');
      // 清空缓存数据
      this.$store.dispatch('pages/fetchAppStore');
      uni.switchTab({
        url: '/pages/index/index'
      });
    },
    // 获取模块配置信息
    async getPageDetail(pageId) {
      return await this.$http({
        login: true,
        alarm: true,
        error: false,
        report: false,
        url: '/product/page/app/detail',
        method: 'get',
        data: {
          pageId
        }
      }).then((res) => {
        return res.data || {};
      }).catch(() => {
        return {};
      });
    },
    getVideoInfo(videoUrl) {
      return new Promise((resolve, reject) => {
        // 判断沉浸式视频的视频是否可播放，可以播放则跳转到沉浸式视频页，不可播放则跳转到普通广告页
        const fileUrl = videoUrl || this.videoUrl;
        uni.downloadFile({
          url: `${fileUrl}?x-oss-process=video/snapshot,t_0,w_1,h_1`,
          success: (file) => {
            console.log('获取视频信息-> ', file.statusCode);
            if (file.statusCode >= 200 && file.statusCode < 300) {
              this.isImmersive = true;
              resolve();
            } else {
              this.isImmersive = false;
              resolve();
            }
          },
          fail: () => {
            this.isImmersive = false;
            resolve();
          }
        });
      });
    },
    toChannels() {
      const { channels } = this.pageModule;
      const params = {
        ...this.query,
        previousStatus: 2
      };
      const query = this.$tools.object2param(params);
      if (channels && channels.videoUrl) {
        uni.getChannelsLiveInfo({
          finderUserName: channels.channelsId,
          success: (res) => {
            // 2直播中 3直播结束
            if (res.status === 2) {
              console.log('前往视频号页面-> ', query);
              uni.navigateTo({
                url: `/packages/channels/index?${query}`
              });
            } else {
              this.handleToStayPopup();
            }
          },
          fail: (res) => {
            console.log('获取直播信息失败', res);
            this.handleToStayPopup();
          }
        });
      } else {
        this.handleToStayPopup();
      }
    },

    handleToStayPopup() {
      const isStayPopup = this.exitPopupList && this.exitPopupList.length > 0 && this.exitPopupIndex < this.exitPopupList.length;
      if (isStayPopup) {
        // 配置有挽留页
        this.toStayPopup();
      } else {
        this.isStay();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
  .x-lazy-loading{ opacity: 0;}
</style>
